package android.rockchip.update.tasks;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.PowerManager;
import android.rockchip.update.RomUpdate;
import android.rockchip.update.service.R;
import android.rockchip.update.utils.Constants;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class GenerateRecoveryScript extends AsyncTask<Void, String, Boolean> implements Constants {

    public static final String TAG = "GenerateRecoveryScript";
    private static String SCRIPT_FILE = "/cache/recovery/openrecoveryscript";
    private static String NEW_LINE = "\n";
    private String mFilename;
    private StringBuilder mScript = new StringBuilder();
    private String mScriptOutput;
    private Context mContext;
    private ProgressDialog mLoadingDialog;
    private String localUpdateFile = "";

    public GenerateRecoveryScript(Context context) {
        mContext = context;
        mFilename = RomUpdate.getFilename(mContext);
    }

    public GenerateRecoveryScript(Context context, String localPath) {
        mContext = context;
        localUpdateFile = localPath;
    }

    @Override
    protected void onPreExecute() {
        mLoadingDialog = new ProgressDialog(mContext.getApplicationContext());
        mLoadingDialog.setCancelable(false);
        mLoadingDialog.setIndeterminate(true);
        mLoadingDialog.setMessage(mContext.getApplicationContext().getString(R.string.rebooting));
        mLoadingDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        mLoadingDialog.show();

//        if (Preferences.getWipeData(mContext)) {
//            mScript.append("wipe data" + NEW_LINE);
//        }
//        if (Preferences.getWipeCache(mContext)) {
//            mScript.append("wipe cache" + NEW_LINE);
//        }
//        if (Preferences.getWipeDalvik(mContext)) {
//            mScript.append("wipe dalvik" + NEW_LINE);
//        }

//        mScript.append("install " + "/sdcard" + File.separator
//                + OTA_DOWNLOAD_DIR + File.separator + mFilename + NEW_LINE);
//
//        File installAfterFlashDir = new File("/sdcard" + File.separator
//                + OTA_DOWNLOAD_DIR + File.separator + INSTALL_AFTER_FLASH_DIR);
//
//        File[] filesArr = installAfterFlashDir.listFiles();
//        if (filesArr != null && filesArr.length > 0) {
//            for (int i = 0; i < filesArr.length; i++) {
//                mScript.append(NEW_LINE + "install " + "/sdcard" + File.separator
//                        + OTA_DOWNLOAD_DIR + File.separator
//                        + INSTALL_AFTER_FLASH_DIR + File.separator + filesArr[i].getName());
//                if (DEBUGGING)
//                    Log.e(TAG, "install " + "/sdcard" + File.separator
//                            + OTA_DOWNLOAD_DIR + File.separator
//                            + INSTALL_AFTER_FLASH_DIR + File.separator + filesArr[i].getName());
//            }
//        }
//
//        if (Preferences.getDeleteAfterInstall(mContext)) {
//            mScript.append(NEW_LINE + "cmd rm -rf " + "/sdcard" + File.separator
//                    + OTA_DOWNLOAD_DIR + File.separator
//                    + INSTALL_AFTER_FLASH_DIR + File.separator + mFilename + NEW_LINE);
//        }
//
//        mScriptOutput = mScript.toString();
        if (TextUtils.isEmpty(localUpdateFile)) {
            installPackage(mContext, "/mnt/internal_sd/OTAUpdates/" + RomUpdate.getFilename(mContext));
        } else {
            installPackage(mContext, localUpdateFile);
        }
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        // Try create a dir in the cache folder Without root
//        String check = Tools.shell("mkdir -p /cache/recovery/; echo $?", false);
//
//        // If not 0, then permission was denied
//        if (!check.equals("0")) {
//            // Run as root
//            Tools.shell("mkdir -p /cache/recovery/; echo $?", true);
//            Tools.shell("echo \"" + mScriptOutput + "\" > " + SCRIPT_FILE + "\n", true);
//        } else {
//            // Permission was enabled, run without root
//            Tools.shell("echo \"" + mScriptOutput + "\" > " + SCRIPT_FILE + "\n", false);
//        }
        return true;
    }

    @Override
    protected void onPostExecute(Boolean value) {
        mLoadingDialog.cancel();
//        Tools.recovery(mContext);
    }

    private static File RECOVERY_DIR = new File("/cache/recovery");
    private static File UPDATE_FLAG_FILE = new File(RECOVERY_DIR, "last_flag");
    private static File COMMAND_FILE = new File(RECOVERY_DIR, "command");
    private static File LOG_FILE = new File(RECOVERY_DIR, "log");

    public static void installPackage(Context context, String filePath) {
        try {
            Log.e(TAG, "999999 !!! REBOOTING TO INSTALL " + filePath + " !!!");
            String arg = "--update_package=" + filePath;
            writeFlagCommand(filePath);
            bootCommand(context, arg);
            Log.e(TAG, "999999 !!! readFlagCommand " + readFlagCommand() + " !!!");
        } catch (IOException e) {
            Log.e(TAG, "999999 installPackage fail, " + e);
            e.printStackTrace();
        }
    }

    public static void writeFlagCommand(String path) throws IOException {
        RECOVERY_DIR.mkdirs();
        UPDATE_FLAG_FILE.delete();
        FileWriter writer = new FileWriter(UPDATE_FLAG_FILE);
        try {
            writer.write("updating$path=" + path);
        } finally {
            writer.close();
        }
    }

    private static void bootCommand(Context context, String arg) throws IOException {
        RECOVERY_DIR.mkdirs();  // In case we need it
        COMMAND_FILE.delete();  // In case it's not writable
        LOG_FILE.delete();

        FileWriter command = new FileWriter(COMMAND_FILE);
        try {
            command.write(arg);
            command.write("\n");
            command.write("--locale=zh_CN");
            command.write("\n");
        } finally {
            command.close();
        }

        // Having written the command file, go ahead and reboot
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        pm.reboot("recovery");

        throw new IOException("Reboot failed (no permissions?)");
    }

    public static String readFlagCommand() {
        if (UPDATE_FLAG_FILE.exists()) {
            char[] buf = new char[128];
            int readCount = 0;
            try {
                FileReader reader = new FileReader(UPDATE_FLAG_FILE);
                readCount = reader.read(buf, 0, buf.length);
                Log.e(TAG, "readCount = " + readCount + " buf.length = " + buf.length);
            } catch (IOException e) {
                Log.e(TAG, "can not read /cache/recovery/flag!");
            } finally {
                UPDATE_FLAG_FILE.delete();
            }

            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < readCount; i++) {
                if (buf[i] == 0) {
                    break;
                }
                sBuilder.append(buf[i]);
            }
            return sBuilder.toString();
        } else {
            return null;
        }
    }

}